/**
 * 各类数据库操作
 */
package service

import (
	"log"
	"sync"

	jsvmcore "gitee.com/xiaoa7/jsvm-core"
	"github.com/dop251/goja"
)

type (
	//数据库连接接口
	ServiceFace interface {
		//连接数据库/服务
		Connect(key string, params ...string) error
		//释放连接
		Destory() error
	}
)

var (
	//数据库连接资源池
	ServicesPool = new(sync.Map)
)

// 注册数据库连接/服务
func RegisteService(key string, db interface{}) {
	if _db, ok := db.(ServiceFace); ok {
		ServicesPool.Store(key, _db)
	} else {
		log.Println(key, "没有实现ServiceFace")
	}
}

// 注册数据库连接/服务
func Destory(key string) {
	if v, ok := ServicesPool.Load(key); ok {
		if db, ok := v.(ServiceFace); ok {
			db.Destory()
		}
	}
}

// 获得数据库连接/服务
func GetService(key string) interface{} {
	if v, ok := ServicesPool.Load(key); ok {
		if db, ok := v.(ServiceFace); ok {
			return db
		}
	}
	return nil
}

// 关闭所有打开的数据库/服务
func DestoryAll() {
	ServicesPool.Range(func(k, v interface{}) bool {
		if db, ok := v.(ServiceFace); ok {
			db.Destory()
		}
		return true
	})
}

func init() {
	jsvmcore.RegisterObject("service", map[string]jsvmcore.HandleFn{
		"destoryAll": func(vm *jsvmcore.JsVM) jsvmcore.JsVmFn {
			return func(params ...interface{}) goja.Value {
				DestoryAll()
				return vm.State.ToValue("ok")
			}
		},
	})
}
